/**
 * 路由守卫
 */
import type { Router } from 'vue-router'
import useAdminStore from '../../store/adminStore.ts'
import useUserStore from "../../store/userStore";
import { apiAdminInfo } from "../../api/user";
import { addRoutes, formatRoutes } from "./routerFormat";

// 添加keepAlive缓存
function addKeepAlive(route: any) {
    const adminStore = useAdminStore()
    if (route.meta && route.meta.keepAlive) {
        adminStore.ADD_KEEPALIVES(route.matched[route.matched.length - 1].components.default.name)
    }
}

// 路由白名单
const whiteList = ['/login', '/exception/403', '/exception/403', '/exception/403']

export default function routerGuard(router: Router) {
    /**前置守卫*/
    router.beforeEach(async (to, from, next) => {
        const { token, userInfo, SET_USER_INFO, SET_PREM, SET_MENUS, SET_ROUTES } = useUserStore();
        const hasToken = token || localStorage.getItem('token')
        if (hasToken) {
            if (to.path === '/login') {
                next({ path: '/' })
            } else {
                if (userInfo.account) {
                    next(); // vuex中有用户信息，证明用户登录状态是有效的
                } else {
                    // 重新请求接口拿用户信息
                    const { data } = await apiAdminInfo();
                    const { menus, prem } = data;
                    const routes = formatRoutes(menus);
                    addRoutes(routes);
                    SET_MENUS(menus);
                    SET_ROUTES(routes);
                    SET_PREM(prem);
                    SET_USER_INFO(data);
                    next({ ...to, replace: true });
                }
            }
        } else {
            if (whiteList.indexOf(to.path) !== -1) {
                // 不是-1就证明存在白名单里，不管你有没有令牌，都直接去到白名单路由对应的页面
                next()
            } else {
                // 如果这个页面不在白名单里，直接跳转到登录页面
                next(`/login?redirect=${ to.path }`)
            }
        }
    })

    /**后置守卫*/
    router.afterEach((to, from, failure) => {
        addKeepAlive(to) // 添加keepAlive缓存
    })
}
